package cn.mrlong.base.utils;

import android.content.Context;

import org.apache.tools.zip.ZipFile;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipException;


/**
 * Created by BINGO on 2017/10/10.
 */

public class ZipUtils {

    public interface CallBackProgress {
        void start();

        void end();
    }

    /**
     * 使用Apache工具包解压缩zip文件
     *
     * @param sourceFilePath   指定的解压缩文件地址
     * @param targetDirPath    指定的解压缩目录地址
     * @param context
     * @param callBackProgress
     * @throws IOException
     * @throws FileNotFoundException
     * @throws ZipException
     */
    public static void uncompressFile(String sourceFilePath, String targetDirPath, Context context, CallBackProgress callBackProgress)
            throws IOException, FileNotFoundException, ZipException {
        BufferedInputStream bis;
        ZipFile zf = new ZipFile(sourceFilePath, "GBK");
        Enumeration e = zf.getEntries();
        callBackProgress.start();
        while (e.hasMoreElements()) {
            org.apache.tools.zip.ZipEntry ze = (org.apache.tools.zip.ZipEntry) e.nextElement();
            String entryName = ze.getName();
            String path = targetDirPath + "/" + entryName;
            if (ze.isDirectory()) {
                System.out.println("正在创建解压目录 - " + entryName);
                File decompressDirFile = new File(path);
                if (!decompressDirFile.exists()) {
                    decompressDirFile.mkdirs();
                }
            } else {
                System.out.println("正在创建解压文件 - " + entryName);
                String fileDir = path.substring(0, path.lastIndexOf("/"));
                File fileDirFile = new File(fileDir);
                if (!fileDirFile.exists()) {
                    fileDirFile.mkdirs();
                }
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetDirPath + "/" + entryName));
                bis = new BufferedInputStream(zf.getInputStream(ze));
                byte[] readContent = new byte[1024];
                int readCount = bis.read(readContent);
                while (readCount != -1) {
                    bos.write(readContent, 0, readCount);
                    readCount = bis.read(readContent);
                }
                bos.close();
            }
        }
        zf.close();
        System.out.println("正在创建解 - 解压完成");
        //amapauto9这个目录名字可能变更
        deleteDir("/sdcard/amapauto9");//删除指定目录
        copyDirectiory(context.getCacheDir() + "/amapauto8", "/sdcard/amapauto9");//拷贝到指定的目录
        //reName(callBackProgress);//重命名文件夹

    }

    // 复制文件
    public static void copyFile(File sourceFile, File targetFile)
            throws IOException {
        // 新建文件输入流并对它进行缓冲
        FileInputStream input = new FileInputStream(sourceFile);
        BufferedInputStream inBuff = new BufferedInputStream(input);

        // 新建文件输出流并对它进行缓冲
        FileOutputStream output = new FileOutputStream(targetFile);
        BufferedOutputStream outBuff = new BufferedOutputStream(output);

        // 缓冲数组
        byte[] b = new byte[1024 * 5];
        int len;
        while ((len = inBuff.read(b)) != -1) {
            outBuff.write(b, 0, len);
        }
        // 刷新此缓冲的输出流
        outBuff.flush();

        //关闭流
        inBuff.close();
        outBuff.close();
        output.close();
        input.close();
    }

    // 复制文件夹
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        // 新建目标目录
        (new File(targetDir)).mkdirs();
        // 获取源文件夹当前下的文件或目录
        File[] file = (new File(sourceDir)).listFiles();
        for (int i = 0; i < file.length; i++) {
            System.out.println("正在创建 - 复制中" + file[i].getAbsolutePath() + "/" + file[i].getName());
            if (file[i].isFile()) {
                // 源文件
                File sourceFile = file[i];
                // 目标文件
                File targetFile = new
                        File(new File(targetDir).getAbsolutePath()
                        + File.separator + file[i].getName());
                copyFile(sourceFile, targetFile);
            }
            if (file[i].isDirectory()) {
                // 准备复制的源文件夹
                String dir1 = sourceDir + "/" + file[i].getName();
                // 准备复制的目标文件夹
                String dir2 = targetDir + "/" + file[i].getName();
                copyDirectiory(dir1, dir2);
            }
        }
        System.out.println("正在创建 - 复制完成");
    }


    //删除文件夹和文件夹里面的文件
    public static void deleteDir(final String pPath) {
        File dir = new File(pPath);
        deleteDirWihtFile(dir);
        System.out.println("正在创建 - 删除" + pPath);
    }

    public static void deleteDirWihtFile(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;
        for (File file : dir.listFiles()) {
            if (file.isFile())
                file.delete(); // 删除所有文件
            else if (file.isDirectory())
                deleteDirWihtFile(file); // 递规的方式删除文件夹
        }
        dir.delete();// 删除目录本身
    }

    /**
     * 文件重命名
     *
     * @param callBackProgress
     */
    private static void reName(CallBackProgress callBackProgress) {
        File oleFile = new File("/sdcard/amapautotmp"); //要重命名的文件或文件夹
        File newFile = new File("/sdcard/amapauto9");  //重命名为zhidian1
        System.out.println("正在创建 - 重命名");
        boolean flag = oleFile.renameTo(newFile);  //执行重命名
        System.out.println("正在创建 - 重命名" + (flag ? "成功" : "失败"));
        callBackProgress.end();
    }
}
